package com.health.viewscontrols.medical.device.bf;

import android.bluetooth.BluetoothGatt;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.HexUtil;
import com.health.tablebean.BTDevice;
import com.health.viewscontrols.NovaApplication;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.nova.health.ble.callback.OnDeviceConnectChangedListener;
import com.novabluetooth.data.DeviceShowSaveData;
import com.novabluetooth.services.BluetoothConstant;
import com.novabluetooth.views.twj.PwBean;

import java.util.List;
import java.util.UUID;

/**
 * 血脂（E家医护）
 */
public class BFEjyhShyActivity extends BaseDeviceActivity {

//    public final static UUID UUID_SERVICE_PW =
//            UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");//蓝牙设备的Service的UUID --0000ffe0
//    public final static UUID UUID_NOTIFY_PW =
//            UUID.fromString("0000fff6-0000-1000-8000-00805f9b34fb");//蓝牙设备的Characteristic的UUID --0000ffe1

    public final static UUID UUID_SERVICE_PW =
            UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");//蓝牙设备的Service的UUID --0000ffe0
    public final static UUID UUID_NOTIFY_PW =
            UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb");//蓝牙设备的Characteristic的UUID --0000ffe1
    public final static UUID UUID_WRITE_PW =
            UUID.fromString("0000fff2-0000-1000-8000-00805f9b34fb");//蓝牙设备的Characteristic的UUID --0000ffe1

    private long firstTime = 0;
    private BleDevice fastBleDevice;
    StringBuilder sbData;

    @Override
    public void doBusiness() {
        tv_operation_tips.setText(com.nova.health.ble.R.string.bf_ejyh);

        BleManager.getInstance().init(getApplication());
        BleManager.getInstance()
                .enableLog(true)
                .setReConnectCount(1, 5000)
                .setConnectOverTime(10000)
                .setOperateTimeout(5000);
        startDevice();
    }


    private void connectDevice() {
        mBleDevice.setConnect(true);
        mBleDevice.setMAC(deviceEnum.getMac());
        mBleDevice.connect(deviceEnum.getMac());
    }

    @Override
    public void startDevice() {
        sbData = new StringBuilder();

        if (fastBleDevice == null) {
            showProgressDialog("正在连接" + deviceEnum.getTitle());
//            connectionPwBle();
            BleManager.getInstance().scan(new BleScanCallback() {
                @Override
                public void onScanStarted(boolean success) {
                }

                @Override
                public void onLeScan(BleDevice bleDevice) {
                    super.onLeScan(bleDevice);
                }

                @Override
                public void onScanning(BleDevice bleDevice) {
                    if (bleDevice != null && bleDevice.getMac() != null && deviceEnum.getMac().equals(bleDevice.getMac())) {
                        connectionPwBle();
                    }
                }

                @Override
                public void onScanFinished(List<BleDevice> scanResultList) {

                }
            });
        } else {
            ToastUtils.showShort("设备已连接，请等待测量结果");
            showProgressDialog("等待接收血脂数据");
//            cancelProgressDialog();
        }
    }

    private void connectionPwBle() {
//        showProgressDialog("正在连接血脂设备");
        BleManager.getInstance().connect(deviceEnum.getMac(), new BleGattCallback() {
            @Override
            public void onStartConnect() {
                blueToothState.setText("蓝牙开始连接");
                showProgressDialog("正在连接血脂设备");
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                Log.e(TAG, "onConnectFail: " +  exception.toString());
                blueToothState.setText("蓝牙连接失败");
                connectionPwBle();
//                cancelProgressDialog();
//                getPwNotify(bleDevice);
            }

            @Override
            public void onConnectSuccess(final BleDevice bleDevice, BluetoothGatt gatt, int status) {
                //连接成功
                Log.e(TAG, "onConnectSuccess: " + bleDevice.getMac() );
                blueToothState.setText("蓝牙已连接");
                fastBleDevice = bleDevice;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getPwNotify(bleDevice);
                    }
                }, 500);
                showProgressDialog("等待接收血脂数据");
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                blueToothState.setText("蓝牙已断开连接");
            }
        });
    }

    private void getPwNotify(final BleDevice bleDevice) {
        BleManager.getInstance().notify(bleDevice,
                UUID_SERVICE_PW.toString(),
                UUID_NOTIFY_PW.toString(),
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        Log.e(TAG, "onNotifySuccess: " );
                    }

                    @Override
                    public void onNotifyFailure(BleException exception) {
                        Log.e(TAG, "onNotifyFailure: " +exception.toString());
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        Log.e(TAG, "onCharacteristicChanged: "+ data );
                        //接收数据
                        String hexString = HexUtil.formatHexString(data);
                        Log.e(TAG, "onCharacteristicChanged: "+ hexString );
//                        if ("020602030b03".equals(hexString) || "020602040c03".equals(hexString)) {
//                            return;
//                        }
                        if (!TextUtils.isEmpty(hexString)
                                && hexString.startsWith("02")
                                && hexString.endsWith("03")
                                && hexString.length() < 16) {
                            return;
                        }
                        sbData.append(hexString);
                        Log.e(TAG,"oncharacteristicchanged:"+ sbData );
//                        update(hexString);
                        update(sbData.toString());
                    }
                });
    }

    @Override
    public void update(String hexStr) {
        try {
            // 0228010101659E534E01C20145013600DC7C4142434431323334353637387C3132333435367C4203
//            hexStr = "0228010101659E534E01C20145013600DC7C4142434431323334353637387C3132333435367C4203";
            if (hexStr.length() > 10) {
                StringBuilder stringBuilder = new StringBuilder();
                String startCmd = hexStr.substring(0, 2);
                String endCmd = hexStr.substring(hexStr.length() - 2);
                // 测量指令 01 测量数据
                String cmd = hexStr.substring(4, 6);
                // 数据指令 01血脂
                String dataCmd = hexStr.substring(6, 8);
                // 02 开头； 03 结尾
                if ("02".equals(startCmd) && "03".equals(endCmd)) {
                    if ("01".equals(cmd)) {
                        // 血脂测量
                        if (("01".equals(dataCmd) || "02".equals(dataCmd)) && hexStr.length() >= 26) {
                            String tcData = hexStr.substring(18, 22);
                            String tgData = hexStr.substring(22, 26);
                            String hdlData = hexStr.substring(26, 30);
                            String ldlData = hexStr.substring(30, 34);
                            PwBean pwBean = new PwBean();
                            Log.e(TAG, "测量完成");
                            if ("FFFF".equalsIgnoreCase(tcData)) {
                                ToastUtils.showLong("总胆固醇:测试结果大于测试范围,请重新测量");
                                stringBuilder.append("总胆固醇:测试结果大于测试范围（HI）");
                            } else if ("0000".equals(tcData)) {
                                ToastUtils.showLong("总胆固醇:测试结果小于测试范围,请重新测量");
                                stringBuilder.append("总胆固醇:测试结果小于测试范围（LO）");
                            } else if ("FFFE".equalsIgnoreCase(tcData)) {
                                ToastUtils.showLong("总胆固醇:测试错误,请重新测量");
                                stringBuilder.append("总胆固醇:测试测试错误（OR）");
                            } else  {
                                double tc = Integer.parseInt(tcData, 16) / 100.0;
                                pwBean.setTc(tc);
                                stringBuilder.append("总胆固醇:" + tc + "mmol/L" + "\n");
                            }

                            if ("FFFF".equalsIgnoreCase(tgData)) {
                                ToastUtils.showLong("甘油三酯:测试结果大于测试范围,请重新测量");
                                stringBuilder.append("甘油三酯:测试结果大于测试范围（HI）");
                            } else if ("0000".equals(tgData)) {
                                ToastUtils.showLong("甘油三酯:测试结果小于测试范围,请重新测量");
                                stringBuilder.append("甘油三酯:测试结果小于测试范围（LO）");
                            } else if ("FFFE".equalsIgnoreCase(tgData)) {
                                ToastUtils.showLong("甘油三酯:测试错误,请重新测量");
                                stringBuilder.append("甘油三酯:测试测试错误（OR）");
                            } else  {
                                double tg = Integer.parseInt(tgData, 16) / 100.0;
                                pwBean.setTg(tg);
                                stringBuilder.append("甘油三酯:" + tg + "mmol/L" + "\n");
                            }

                            if ("FFFF".equalsIgnoreCase(hdlData)) {
                                ToastUtils.showLong("高密:测试结果大于测试范围,请重新测量");
                                stringBuilder.append("高密:测试结果大于测试范围（HI）");
                            } else if ("0000".equals(hdlData)) {
                                ToastUtils.showLong("高密:测试结果小于测试范围,请重新测量");
                                stringBuilder.append("高密:测试结果小于测试范围（LO）");
                            } else if ("FFFE".equalsIgnoreCase(hdlData)) {
                                ToastUtils.showLong("高密:测试错误,请重新测量");
                                stringBuilder.append("高密:测试测试错误（OR）");
                            } else  {
                                double hdl = Integer.parseInt(hdlData, 16) / 100.0;
                                pwBean.setHdl(hdl);
                                stringBuilder.append("高密:" + hdl + "mmol/L" + "\n");
                            }

                            if ("FFFF".equalsIgnoreCase(ldlData)) {
                                ToastUtils.showLong("低密:测试结果大于测试范围,请重新测量");
                                stringBuilder.append("低密:测试结果大于测试范围（HI）");
                            } else if ("0000".equals(ldlData)) {
                                ToastUtils.showLong("低密:测试结果小于测试范围,请重新测量");
                                stringBuilder.append("低密:测试结果小于测试范围（LO）");
                            } else if ("FFFE".equalsIgnoreCase(ldlData)) {
                                ToastUtils.showLong("低密:测试错误,请重新测量");
                                stringBuilder.append("低密:测试测试错误（OR）");
                            } else  {
                                double ldl = Integer.parseInt(ldlData, 16) / 100.0;
                                pwBean.setLdl(ldl);
                                stringBuilder.append("低密:" + ldl + "mmol/L" + "\n");
                            }

                            Log.e(TAG, "resultData: " + stringBuilder.toString());
//                            if (pwBean.getTc() > 0 && pwBean.getTg() > 0 && pwBean.getHdl() > 0 && pwBean.getLdl() > 0) {
                            tv_result.setText(pwBean.getTc() + "");
                            //有效数据在存入数据库
                            String json = GsonUtils.toJson(pwBean);
                            Log.e(TAG, "resultData: " + json);
                            long currentTime = System.currentTimeMillis();
                            if (currentTime - firstTime > 2000) {
                                firstTime = currentTime;
                                DeviceShowSaveData.getDataShow(json, BluetoothConstant.PW_01DEVICE_NAME);
                                DeviceShowSaveData.saveXueZhi(json);
                                tv_state.setText("获取测量结果成功");
                                tv_result.setText(stringBuilder.toString());
                            }
                            cancelProgressDialog();
//                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "出错了: " + e.getMessage());
        }
    }

    /**
     * 校验数据是否合规
     *
     * @return 1 合规 ；2 大于测试范围 ；3小于测试范围
     */
    public int checkDataCompliance(String params1, String params2) {
        if ("ff".equals(params1) && "ff".equals(params2)) {
            System.out.println("测试结果大于测试范围");
            return 2;
        } else if ("00".equals(params1) && "00".equals(params2)) {
            System.out.println("测试结果小于测试范围");
            return 3;
        } else {
            return 1;
        }
    }


    @Override
    public void disconnectDevice() {
        try {
            BleManager.getInstance().disconnectAllDevice();
            BleManager.getInstance().destroy();
            fastBleDevice = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
